# -*- coding: utf-8 -*-
"""
@Time ： 2024/10/25 13:32
@Auth ： 刘佳
@File ：logging_config.py
@IDE ：PyCharm
@Motto:日志记录器
"""
# logging_config.py
import logging
from pathlib import Path
from datetime import datetime


# 创建日志记录器
# def setup_logger(name, log_dir):
#     log_dir = Path(log_dir)
#     log_dir.mkdir(parents=True, exist_ok=True)  # 确保日志目录存在
#
#     # 动态生成日志文件路径，包含日期
#     log_file = log_dir / f"{datetime.now().strftime('%Y-%m-%d')}.log"
#
#     logger = logging.getLogger(name)
#
#     # 确保日志记录器只被创建一次
#     if not logger.hasHandlers():
#         logger.setLevel(logging.INFO)  # 设置日志级别
#         handler = logging.FileHandler(log_file, encoding='utf-8')
#         formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
#         handler.setFormatter(formatter)
#         logger.addHandler(handler)
#
#     return logger

# class LogHandler(logging.Handler):
#     def __init__(self, signal):
#         super().__init__()
#         self.signal = signal
#
#     def emit(self, record):
#         msg = self.format(record)
#         self.signal.emit(msg)  # 通过信号发送消息
#
# def setup_logger(name, log_dir, log_signal=None):
#     log_dir = Path(log_dir)
#     log_dir.mkdir(parents=True, exist_ok=True)  # 确保日志目录存在
#
#     # 动态生成日志文件路径，包含日期
#     log_file = log_dir / f"{datetime.now().strftime('%Y-%m-%d')}.log"
#
#     logger = logging.getLogger(name)
#
#     if not logger.hasHandlers():
#         logger.setLevel(logging.INFO)  # 设置日志级别
#         handler = logging.FileHandler(log_file, encoding='utf-8')
#         formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
#         handler.setFormatter(formatter)
#         logger.addHandler(handler)
#
#         # 添加一个自定义的处理程序，用于发送日志到 QTextEdit
#         class SignalHandler(logging.Handler):
#             def emit(self, record):
#                 msg = self.format(record)
#                 if log_signal:
#                     log_signal.emit(msg)  # 发送日志信息到信号
#
#         signal_handler = SignalHandler()
#         signal_handler.setFormatter(formatter)
#         logger.addHandler(signal_handler)  # 添加自定义处理程序
#
#     return logger

class LogHandler(logging.Handler):
    def __init__(self, signal):
        super().__init__()
        self.signal = signal

    def emit(self, record):
        msg = self.format(record)
        self.signal.emit(msg)  # 通过信号发送消息


def setup_logger(name, log_dir, log_signal=None):
    log_dir = Path(log_dir)
    log_dir.mkdir(parents=True, exist_ok=True)  # 确保日志目录存在

    log_file = log_dir / f"{datetime.now().strftime('%Y-%m-%d')}.log"
    logger = logging.getLogger(name)

    if not logger.hasHandlers():
        logger.setLevel(logging.INFO)
        handler = logging.FileHandler(log_file, encoding='utf-8')
        formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
        handler.setFormatter(formatter)
        logger.addHandler(handler)

        if log_signal:
            signal_handler = LogHandler(log_signal)
            signal_handler.setFormatter(formatter)
            logger.addHandler(signal_handler)

    return logger